<?php
namespace App\Domain\Appfc114;

use App\Model\Appfc114\MetaData as ModelMetaData;
use Illuminate\Database\Capsule\Manager as DB;

class MetaData  {

    protected $query;

    function __construct() {
        $this->query = new QueryCommon();
    }

    public function getMetaDataByType($code_type, $order = " sort desc", $type=true)
    {
        $model = new  ModelMetaData();
        $aCode = $model->where("flag",1)->where("active",1)
            ->where("parent_code",$code_type)
            ->orderByRaw($order)
            ->get();
        $rtn = array();
        $i=0;
        foreach($aCode as $item){
            if($type==true) {
                $rtn[$aCode[$i]['key']] = $item['name'];
            }else{
                $rtn[$aCode[$i]['value']] =$item['name'];
            }
            $i++;
        }
        return $rtn;
    }

    /**
     * 以键值对的形式取出基础代码
     * @param int $code_type 基础代码类型
     * @param string $where 补充条件
     * @param int $type 1返回key=>value键值对,2返回vaule=>value键值对
     * @access public
     * @return array 返回数组
     */
    public function getPairBaseCodeByType($code_type, $where = " order by sort desc",$type=true)
    {
        $aCode = DB::table("sys_metadata")
            ->where("flag",1)
            ->where("active",1)
            ->where("parent_code",$code_type)
            ->orderByRaw("sort desc")
            ->get()->toArray();

        $rtn = array();
        for ($i=0, $m=sizeof($aCode); $i < $m; $i++){
            if($type==true) {
                $rtn[$aCode[$i]['code']] = $aCode[$i]['name'];
            }else{
                $rtn[$aCode[$i]['name']] = $aCode[$i]['name'];
            }
        }
        return $rtn;
    }

    /**
     * 根据基础代码查询代码名称
     * @access public
     * @param  $code  基础代码
     * @return array
     */
    public function getNameByCode($code) {
        $codes = explode(",", $code);
        if(count($codes)>1){
            $name = '';
            foreach ($codes as $item) {
                $sql = "SELECT id,code,name FROM %s WHERE code = %d AND flag = 1 ";
                $sql = sprintf($sql, "sys_metadata", $item);
                $arrcode = $this->query->getRow($sql);
                $name .= $arrcode['name'].',';
            }
            $name = substr($name,0,-1);
        }else{
            $sql = "SELECT id,code,name FROM %s WHERE code = %d AND flag = 1 ";
            $sql = sprintf($sql, "sys_metadata", $codes[0]);
            $arrcode = $this->query->getRow($sql);
            $name = $arrcode['name'];
        }
        return $name;
    }

}
